package net.wanho.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.entity.User;
import net.wanho.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final RedisTemplate<String,Object> redisTemplate;

    @Override
    public User findById(Integer id) {
        // 从redis中获取用户信息
        User user = (User) redisTemplate.opsForValue().get("user:id:" + id);
        if (! ObjectUtils.isEmpty(user)){
            return user;
        }

        // 查询数据库
        user = new User(id, "user" + id, "123");
        System.out.println("从数据库中查询用户信息。。。。" + user);

        // 将用户信息存入redis
      	redisTemplate.opsForValue().set("user:id:" + id, user, 2, TimeUnit.MINUTES);

        return user;
    }
}  